package bid.yanhj.yanhaijiang.broadcasreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

/**
 * 广播
 * 应用场景
 * 1 同一个app内部的同一组件内的消息通信
 * （单个或多个线程之间）
 * 2 同一app内部的不同组件之间的消息通信（单个进程）
 * 3 同一app具有多个进程的不同组件之间通信
 * 4 不同app之间的组件消息通信
 * 5 android系统在特定情况下与app之间的消息通信
 *
 * 静态 动态
 * 有序 无序
 *
 * TODO 这有点问题  动态广播
 *
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LanOu";
    private AirPlayReceiver airPlayReceiver;

    private Button orderBtn, broadcastBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        airPlayReceiver = new AirPlayReceiver();
        IntentFilter intentFilter  = new IntentFilter();
        intentFilter.addAction("android.intent.action.AIRPLANE_MODE");
        // 广播就注册好了
        registerReceiver(airPlayReceiver, intentFilter);

        orderBtn = this.<Button>findViewById(R.id.send_order_broadcast_btn);
        orderBtn.setOnClickListener(this);

        // 有序
        broadcastBtn = this.<Button>findViewById(R.id.send_dese_broadcast_btn);
        broadcastBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_order_broadcast_btn:
                Intent orderIntent = new Intent();
                // 注册类型
                orderIntent.setAction("my.receiver");
                sendBroadcast(orderIntent);
                break;
            case R.id.send_dese_broadcast_btn:
                Intent broadcastIntent = new Intent();
                // 注册类型
                broadcastIntent.setAction("my.receiver");
                sendOrderedBroadcast(broadcastIntent, null,null,null,0,"这是初始值",null);
                break;
        }
    }

    // 动态注册
    class AirPlayReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: --动态");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册
        unregisterReceiver(airPlayReceiver);
    }
}
